#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QMessageBox>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui_(new Ui::MainWindow)
{
    ui_->setupUi(this);
    serialManager_ = new SerialManager(this);
    modbusRTU_ = new ModbusRTU(serialManager_, this);
    logManager_ = new LogManager(ui_->textEdit_log, this);

    initMainWindow();
    initSignalSlot();
    serialManager_->autoFillSerialPorts(ui_->comboBox_serial);
}

MainWindow::~MainWindow()
{
    // 显式断开信号槽连接，避免野指针
    disconnect(serialManager_, nullptr, this, nullptr);
    disconnect(modbusRTU_, nullptr, this, nullptr);
    disconnect(logManager_, nullptr, this, nullptr);

    delete ui_;
}

void MainWindow::initMainWindow()
{
    setWindowTitle("Modbus主站");
    setWindowIcon(QIcon(":/resource/image/modbus.png"));
    ui_->logo->setIcon(QIcon(":/resource/image/noconnect.png"));
    ui_->logo->setStyleSheet("QPushButton { background-color: transparent; }");

    QString buttonStyle = "QPushButton { text-align: center; padding: 5px 15px; qproperty-iconSize: 24px 24px; }";
    ui_->exportButton->setIcon(QIcon(":/resource/image/export.png"));
    ui_->exportButton->setIconSize(QSize(24, 24));
    ui_->exportButton->setStyleSheet(buttonStyle);

    ui_->deleteButton->setIcon(QIcon(":/resource/image/delete.png"));
    ui_->deleteButton->setIconSize(QSize(24, 24));
    ui_->deleteButton->setStyleSheet(buttonStyle);

    ui_->readButton->setIcon(QIcon(":/resource/image/read.png"));
    ui_->readButton->setIconSize(QSize(24, 24));
    ui_->readButton->setStyleSheet(buttonStyle);

    ui_->writeButton->setIcon(QIcon(":/resource/image/write.png"));
    ui_->writeButton->setIconSize(QSize(24, 24));
    ui_->writeButton->setStyleSheet(buttonStyle);
}

void MainWindow::initSignalSlot()
{
    connect(ui_->connectButton, &QPushButton::clicked, this, &MainWindow::onConnectButtonClicked);
    connect(ui_->readButton, &QPushButton::clicked, this, &MainWindow::onReadButtonClicked);
    connect(ui_->writeButton, &QPushButton::clicked, this, &MainWindow::onWriteButtonClicked);
    connect(ui_->deleteButton, &QPushButton::clicked, this, &MainWindow::onDeleteButtonClicked);
    connect(ui_->exportButton, &QPushButton::clicked, this, &MainWindow::onExportButtonClicked);
    connect(serialManager_, &SerialManager::connectionStatusChanged, this, &MainWindow::updateConnectionStatus);
    connect(modbusRTU_, &ModbusRTU::responseReady, this, &MainWindow::handleModbusResponse);
    connect(modbusRTU_, &ModbusRTU::errorOccurred, this, &MainWindow::handleModbusError);
}

void MainWindow::onConnectButtonClicked()
{
    if (isConnected_) {
        serialManager_->closeSerialPort();
    } else {
        SerialParams params;
        params.portName = ui_->comboBox_serial->currentText();
        params.baudRate = ui_->comboBox_baud->currentText().toInt();
        params.dataBits = ui_->comboBox_data->currentText().toInt();
        params.parity = ui_->comboBox_parity->currentText();
        params.stopBits = ui_->comboBox_stop->currentText();

        if (!serialManager_->openSerialPort(params)) {
            QMessageBox::warning(this, "错误", "连接失败: " + serialManager_->lastError());
        }
    }
}

void MainWindow::onReadButtonClicked()
{
    if (!isConnected_) {
        QMessageBox::information(this, "提示", "请先建立连接");
        return;
    }

    ModbusParams params;
    params.slaveAddr = ui_->spinBox_slaveAddr->value();
    params.startAddr = ui_->spinBox_startAddr->value();
    params.count = ui_->spinBox_count->value();
    params.function = ui_->comboBox_function->currentText();
    params.timeout = ui_->spinBox_timeout->value();
    params.retryCount = ui_->spinBox_num->value();

    modbusRTU_->readData(params);
}

void MainWindow::onWriteButtonClicked()
{
    if (!isConnected_) {
        QMessageBox::information(this, "提示", "请先建立连接");
        return;
    }

    ModbusParams params;
    params.slaveAddr = ui_->spinBox_slaveAddr->value();
    params.startAddr = ui_->spinBox_startAddr->value();
    params.count = ui_->spinBox_count->value();
    params.function = ui_->comboBox_function->currentText();
    params.data = ui_->textEdit_write->toPlainText().trimmed();
    params.timeout = ui_->spinBox_timeout->value();
    params.retryCount = ui_->spinBox_num->value();

    modbusRTU_->writeData(params);
}

void MainWindow::onDeleteButtonClicked()
{
    logManager_->clearLog();
    QMessageBox::information(this, "提示", "日志已清空");
}

void MainWindow::onExportButtonClicked()
{
    logManager_->exportLog();
}

void MainWindow::updateConnectionStatus(bool connected, const QDateTime &timestamp)
{
    if (!isVisible()) return; // 窗口已关闭时不处理

    isConnected_ = connected;
    if (connected) {
        ui_->connectStatus->setText("已连接");
        ui_->logo->setIcon(QIcon(":/resource/image/connect.png"));
        ui_->connectButton->setText("断开");
        logManager_->addLog(timestamp.toString("[yyyy-MM-dd HH:mm:ss]") + " 成功连接串口: " + serialManager_->currentPortName());
    } else {
        ui_->connectStatus->setText("未连接");
        ui_->logo->setIcon(QIcon(":/resource/image/noconnect.png"));
        ui_->connectButton->setText("连接");
        logManager_->addLog(timestamp.toString("[yyyy-MM-dd HH:mm:ss]") + " 串口已断开\n");
    }
}

void MainWindow::handleModbusResponse(const QString &response)
{
    logManager_->addLog(response);
}

void MainWindow::handleModbusError(const QString &error)
{
    logManager_->addLog("错误: " + error);
    QMessageBox::warning(this, "错误", error);
}
